#! /bin/bash
# o programa recebe 4 parametros ( as coordenadas dos dois centroids iniciais)
# @1 - x1
# @2 - y1
# @3 - x2
# @4 - y2


c1x=$1
c1y=$2
c2x=$3
c2y=$4


cluster1=""
cluster2=""
distancia1=""
distancia2=""
contrib1x=0
contrib1y=0
n1=0
contrib2x=0
contrib2y=0
n2=0


IFS=,
while read x y 
do
	dist1=$(echo "scale=2; sqrt(($x - $c1x)^2 +($y - $c1y)^2)" | bc )
	dist2=$(echo "scale=2; sqrt(($x - $c2x)^2 +($y - $c2y)^2)" | bc )
	distancia1="$distancia1 $dist1 "
	distancia2="$distancia2 $dist2 "

	
	result=$(echo " scale=2; r = 2;  if($dist2 > $dist1) r=1; r" | bc)
	if [ "$result" -eq 1 ] 
	then
		cluster1="$cluster1 1 "
		cluster2="$cluster2 0 "
		contrib1x=$( echo "scale=2; $contrib1x + $x" | bc)
		contrib1y=$( echo "scale=2; $contrib1y + $y" | bc)
		n1=$((n1 + 1))
	else
		cluster1="$cluster1 0 "
		cluster2="$cluster2 1 "
		contrib2x=$( echo "scale=2; $contrib2x + $x" | bc)
		contrib2y=$( echo "scale=2; $contrib2y + $y" | bc)
		n2=$((n2 + 1))
	fi 

done < tab4

echo "centroids iniciais"
echo $1 , $2
echo $3 , $4

echo "distancias:"
echo $distancia1
echo $distancia2


echo "Clusters:"
echo $cluster1
echo $cluster2

echo "Novos Centroids:"
echo C1: $(echo "scale=2; $contrib1x / $n1 " | bc) , $(echo "scale=2; $contrib1y / $n1 " | bc)
echo C2: $(echo "scale=2; $contrib2x / $n2 " | bc) , $(echo "scale=2; $contrib2y / $n2 " | bc)
 
